<?php

namespace App\Model;

use IMooc\Database\MySQLi;
use IMooc\Factory;
use IMooc\Model;

class MUser extends Model
{
    protected string $table = 'user';

    public int $id;
    public string $name;
    public string $mobile;
    public string $regtime;
    public ?int $serial_no;

    protected ?object $db;

    public function __construct($id)
    {
        $this->db = new MySQLi();
        $this->db->connect('127.0.0.1', 'root', 'root', 'test');
        $res = $this->db->query("select * from user where id = $id limit 1");
        $data = $res->fetch_assoc();

        // 数据库数据 赋值给 类成员属性
        $this->id = $data['id'];
        $this->name = $data['name'];
        $this->mobile = $data['mobile'];
        $this->regtime = $data['regtime'];
        $this->serial_no = $data['serial_no'];
    }

    public function __destruct()
    {
        $sql = <<<sql
update $this->table set name = '$this->name', mobile = '$this->mobile', regtime = '$this->regtime', serial_no = '$this->serial_no'
where id = $this->id limit 1;
sql;
        $this->db->query($sql);
    }

    function getInfo($id): false|array|null
    {
        return Factory::getDatabase('slave')->query("select * from user where id =$id limit 1")->fetch_assoc();
    }

    function create($user): int
    {
        //insert to database
        $userid = 1;
        $this->notify($user);
        return $userid;
    }
}